
package com.hlkj.pay.app.merchant.ext.impl.helipay.handler;
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

import com.hlkj.framework.common.pojo.CommonResult;
import com.hlkj.framework.common.util.json.JsonUtils;
import com.hlkj.framework.http.template.OkHttpTemplate;
import com.hlkj.pay.app.merchant.ext.dto.access.ChannelMerchantAccessAuthQueryContext;
import com.hlkj.pay.app.merchant.ext.dto.access.ChannelMerchantBusinessContext;
import com.hlkj.pay.app.merchant.ext.impl.helipay.dto.HeliPayConfig;
import com.hlkj.pay.app.merchant.ext.impl.helipay.dto.req.HeliPayAuthQueryRes;
import com.hlkj.pay.app.merchant.ext.impl.helipay.dto.req.HeliWechatConfigInitRes;
import com.hlkj.pay.dto.merchant.MerchantWechatConfigDto;
import com.hlkj.pay.dto.pay.PayCommonAppDto;
import com.hlkj.pay.enums.MerchantEnum;
import com.hlkj.pay.enums.PayEnums;
import com.hlkj.pay.infrastructure.model.merchant.MerchantAccessAuthDO;
import com.hlkj.pay.infrastructure.model.merchant.MerchantAccessInfoDO;
import com.hlkj.pay.infrastructure.model.pay.PayChannelRequestDO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.core.utils.StringPool;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author HlpayTeam
 * @date 2024/10/16 9:10
 */
@Slf4j
@Repository
@RequiredArgsConstructor
@Component
public class HeliPayMerchantAccessConfigHandler extends HeliPayMerchantCommonParamsHandle {

    private final OkHttpTemplate okHttpTemplate;

    @Value("${hlkj.domain}")
    private String domain;

    /**
     * 微信参数配置查询
     *
     * @param channelMerchantBusinessContext
     */
    public void processSubMerInfoQuery(ChannelMerchantBusinessContext channelMerchantBusinessContext) {
        CommonResult<HeliPayConfig> heliPayConfigCommonResult = heliPayConfig(channelMerchantBusinessContext.getProviderChannelConfig(), channelMerchantBusinessContext.isTest());
        // 配置转换
        if (!heliPayConfigCommonResult.isSuccess()) {
            channelMerchantBusinessContext.setRemark(heliPayConfigCommonResult.getMsg());
            channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
            return;
        }
        HeliPayConfig heliPayConfig = heliPayConfigCommonResult.getData();
        // 1. 数据初始化
        MerchantAccessInfoDO merchantAccessInfo = channelMerchantBusinessContext.getMerchantAccessDto().getMerchantAccessInfo();
        try {
            List<MerchantAccessAuthDO> merchantAccessAuthList = new ArrayList<>();

            List<String> appPayTypes = new ArrayList<>();
            appPayTypes.add("ALIPAY");
            appPayTypes.add("WXPAY");
            appPayTypes.add("JDPAY");
            appPayTypes.add("UNIONPAY_ALL");
            String accessUrl = accessUrl(channelMerchantBusinessContext.isTest());
            appPayTypes.stream().forEach(appPayType -> {
                Map<String, String> params = new HashMap<>();
                params.put("merchantNo", merchantAccessInfo.getSubMchId());
                params.put("orderNo", System.currentTimeMillis() + "");
                params.put("appPayType", appPayType);
                CommonResult<HeliPayAuthQueryRes> commonResult = heliPayAccessRequest(accessUrl, "appApplyQuery", heliPayConfig, JsonUtils.toJsonString(params),
                        HeliPayAuthQueryRes.class);
                log.info("合利宝 报备查询 返回参数 :{}", JsonUtils.toJsonString(commonResult));
                HeliPayAuthQueryRes heliPayAuthQueryRes = commonResult.getData();
                if (heliPayAuthQueryRes != null) {
                    if ("SUCCESS".equals(heliPayAuthQueryRes.getStatus())) {
                        List<HeliPayAuthQueryRes.HeliPayPartnerAuthQueryRes> threePartnerNoData = heliPayAuthQueryRes.getThreePartnerNoData();
                        List<HeliPayAuthQueryRes.HeliPayUnionPayAuthQueryRes> unionPayRecords = heliPayAuthQueryRes.getUnionPayRecords();
                        switch (appPayType) {
                            case "UNIONPAY_ALL":
                                if (!CollectionUtils.isEmpty(unionPayRecords)) {
                                    Map<String, List<HeliPayAuthQueryRes.HeliPayUnionPayAuthQueryRes>> collect = unionPayRecords.stream()
                                            .collect(Collectors.groupingBy(heliPayPartnerAuthQueryRes -> heliPayPartnerAuthQueryRes.getSubMerchantNo()));
                                    collect.forEach((key, value) -> {
                                        HeliPayAuthQueryRes.HeliPayUnionPayAuthQueryRes unionPayRecord = value.get(0);
                                        MerchantAccessAuthDO merchantAccessAuthDO = new MerchantAccessAuthDO();
                                        merchantAccessAuthDO.setType(PayEnums.PAY_TYPE.UNION_APY.getCode());
                                        merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.WAIT_CONFIRM.getCode());
                                        merchantAccessAuthDO.setAuthUrl(unionPayRecord.getQrCode());
                                        merchantAccessAuthDO.setSubMchId(unionPayRecord.getSubMerchantNo());
                                        merchantAccessAuthList.add(merchantAccessAuthDO);
                                    });
                                }
                                break;
                            default:
                                if (!CollectionUtils.isEmpty(threePartnerNoData)) {
                                    Map<String, List<HeliPayAuthQueryRes.HeliPayPartnerAuthQueryRes>> collect = threePartnerNoData.stream()
                                            .collect(Collectors.groupingBy(heliPayPartnerAuthQueryRes -> heliPayPartnerAuthQueryRes.getThreePartnerNo() + "_"
                                                    + heliPayPartnerAuthQueryRes.getChannelMerchantNo()));
                                    collect.forEach((key, value) -> {
                                        HeliPayAuthQueryRes.HeliPayPartnerAuthQueryRes partnerAuthQueryRes = value.get(0);

                                        MerchantAccessAuthDO merchantAccessAuthDO = new MerchantAccessAuthDO();
                                        switch (appPayType) {
                                            case "ALIPAY":
                                                merchantAccessAuthDO.setType(PayEnums.PAY_TYPE.ALIPAY.getCode());
                                                break;
                                            case "WXPAY":
                                                merchantAccessAuthDO.setType(PayEnums.PAY_TYPE.WECHAT.getCode());
                                                break;
                                            case "JDPAY":
                                                merchantAccessAuthDO.setType(PayEnums.PAY_TYPE.JDBT.getCode());
                                                break;
                                        }
                                        if (StringUtils.hasText(partnerAuthQueryRes.getConfirmStatus())) {
                                            switch (partnerAuthQueryRes.getConfirmStatus()) {
                                                case "CONFIRM_REJECTED":
                                                    merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.REJECT.getCode());
                                                    break;
                                                case "CONFIRMING":
                                                    merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.APPROVEING.getCode());
                                                    break;
                                                case "CONFIRM_CONTACT":
                                                    merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.WAIT_CONFIRM.getCode());
                                                    break;
                                                case "CONFIRM_LEGALPERSON":
                                                    merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.WAIT_AUTH.getCode());
                                                    break;
                                                case "CONFIRM_PASSED":
                                                    merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.APPROVE.getCode());
                                                    break;
                                                case "CONFIRM_FREEZED":
                                                    merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.FROZEN.getCode());
                                                    break;
                                                case "CONFIRM_CANCELED":
                                                    merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.CANCEL.getCode());
                                                    break;
                                                default:
                                            }
                                        }
                                        else {
                                            merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.APPROVEING.getCode());
                                        }
                                        if (StringUtils.hasText(partnerAuthQueryRes.getAuthorizeStatus())) {
                                            switch (partnerAuthQueryRes.getAuthorizeStatus()) {
                                                case "AUTHORIZED":
                                                    merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.AUTH_SUCCESS.getCode());
                                                    break;
                                                case "AUTHORIZED_FAIL":
                                                    merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.AUTH_FAIL.getCode());
                                                    break;
                                                default:
                                            }
                                        }
                                        merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.WAIT_CONFIRM.getCode());
                                        merchantAccessAuthDO.setSubMchId(partnerAuthQueryRes.getChannelMerchantNo());
                                        merchantAccessAuthDO.setMchId(partnerAuthQueryRes.getThreePartnerNo());
                                        merchantAccessAuthDO.setSerialCode(partnerAuthQueryRes.getReportId());
                                        merchantAccessAuthDO.setChannelJson(JsonUtils.toJsonString(partnerAuthQueryRes));
                                        if (StringUtils.hasText(partnerAuthQueryRes.getQrCodeData())) {
                                            byte[] imageBytes = Base64.getDecoder().decode(partnerAuthQueryRes.getQrCodeData());
                                            merchantAccessAuthDO.setQrCodeArray(imageBytes);
                                        }
                                        merchantAccessAuthDO.setRejectReason(partnerAuthQueryRes.getReportFailedReason());
                                        merchantAccessAuthList.add(merchantAccessAuthDO);
                                    });
                                }
                        }
                    }

                }
            });
            channelMerchantBusinessContext.setAuditStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.WECHAT_CONFIG);
            channelMerchantBusinessContext.setMerchantAccessAuthList(merchantAccessAuthList);
            channelMerchantBusinessContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.APPROVE_SUCCESS);
        }
        catch (Exception e) {
            e.printStackTrace();
            log.error("合利宝商户报备信息查询请求失败,失败信息 message: {}", e.getMessage());
            channelMerchantBusinessContext.setRemark("合利宝商户报备信息查询请求失败,失败信息" + e.getMessage());
            channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
            channelMerchantBusinessContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.APPROVE_REFUSE);
        }
    }

    /**
     * 微信参数配置
     *
     * @param channelMerchantBusinessContext
     */
    public void processWxConfigSetInit(ChannelMerchantBusinessContext channelMerchantBusinessContext) {
        CommonResult<HeliPayConfig> heliPayConfigCommonResult = heliPayConfig(channelMerchantBusinessContext.getProviderChannelConfig(), channelMerchantBusinessContext.isTest());
        // 配置转换
        if (!heliPayConfigCommonResult.isSuccess()) {
            channelMerchantBusinessContext.setRemark(heliPayConfigCommonResult.getMsg());
            channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
            return;
        }
        HeliPayConfig heliPayConfig = heliPayConfigCommonResult.getData();
        // 1. 数据初始化
        MerchantAccessInfoDO merchantAccessInfo = channelMerchantBusinessContext.getMerchantAccessDto().getMerchantAccessInfo();
        try {
            List<PayCommonAppDto> payCommonAppList = channelMerchantBusinessContext.getPayCommonAppList();
            List<PayCommonAppDto> wechatCommonApp = null;
            if (!CollectionUtils.isEmpty(payCommonAppList)) {
                wechatCommonApp = payCommonAppList.stream().filter(payCommonAppDto -> PayEnums.PAY_TYPE.WECHAT.getCode().equals(payCommonAppDto.getPayWayDO().getType()))
                        .collect(Collectors.toList());
            }
            // 没有微信执行 配置完成
            if (CollectionUtils.isEmpty(wechatCommonApp)) {
                channelMerchantBusinessContext.setAuditStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.ALIPAY_AUTH);
                return;
            }
            List<MerchantAccessAuthDO> merchantAccessAuthList = channelMerchantBusinessContext.getMerchantAccessDto().getMerchantAccessAuthList().stream()
                    .filter(merchantAccessAuthDO -> PayEnums.PAY_TYPE.WECHAT.getCode().equals(merchantAccessAuthDO.getType())).collect(Collectors.toList());

            if (CollectionUtils.isEmpty(merchantAccessAuthList)) {
                channelMerchantBusinessContext.setAuditStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.ALIPAY_AUTH);
                return;
            }
            MerchantAccessAuthDO merchantAccessAuthDO1 = merchantAccessAuthList.get(0);
            List<String> appIds = wechatCommonApp.stream().map(wechatCommon -> wechatCommon.getAppId()).collect(Collectors.toList());
            String accessUrl = accessUrl(channelMerchantBusinessContext.isTest());
            Map<String, Object> params = new HashMap<>();
            params.put("merchantNo", merchantAccessInfo.getSubMchId());
            params.put("orderNo", System.currentTimeMillis() + "");
            params.put("appIds", appIds);
            if (!domain.endsWith(StringPool.SLASH)) {
                domain = domain + StringPool.SLASH;
            }
            params.put("authPayDirs", List.of(domain));
            params.put("merchantChannelName", heliPayConfig.getChannelName());
            params.put("operateType", "REPEAT");
            params.put("reportId", merchantAccessAuthDO1.getSerialCode());
            params.put("applyType", heliPayConfig.getApplyType());
            CommonResult<HeliWechatConfigInitRes> commonResult = heliPayAccessRequest(accessUrl, "wxPublicApply", heliPayConfig, JsonUtils.toJsonString(params),
                    HeliWechatConfigInitRes.class);
            log.info("合利宝 微信参数初始化配置 返回参数 :{}", JsonUtils.toJsonString(commonResult));
            channelMerchantBusinessContext.setAuditStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.WECHAT_AUTH);
        }
        catch (Exception e) {
            e.printStackTrace();
            log.error("合利宝微信配置init请求失败,失败信息 message: {}", e.getMessage());
            channelMerchantBusinessContext.setRemark("合利宝微信配置init请求失败,失败信息" + e.getMessage());
            channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
            // channelMerchantBusinessContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.APPROVE_REFUSE);
        }
    }

    public void processWxConfigSetAdd(ChannelMerchantBusinessContext channelMerchantBusinessContext) {
        CommonResult<HeliPayConfig> heliPayConfigCommonResult = heliPayConfig(channelMerchantBusinessContext.getProviderChannelConfig(), channelMerchantBusinessContext.isTest());
        // 配置转换
        if (!heliPayConfigCommonResult.isSuccess()) {
            channelMerchantBusinessContext.setRemark(heliPayConfigCommonResult.getMsg());
            channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
            return;
        }
        HeliPayConfig heliPayConfig = heliPayConfigCommonResult.getData();
        // 1. 数据初始化
        PayChannelRequestDO payChannelRequestDO = new PayChannelRequestDO();
        channelMerchantBusinessContext.setPayChannelRequestDO(payChannelRequestDO);
        MerchantAccessInfoDO merchantAccessInfo = channelMerchantBusinessContext.getMerchantAccessDto().getMerchantAccessInfo();
        MerchantWechatConfigDto merchantWechatConfigDto = channelMerchantBusinessContext.getMerchantWechatConfigDto();
        MerchantAccessAuthDO merchantAccessAuth = channelMerchantBusinessContext.getMerchantAccessAuth();
        try {

            String accessUrl = accessUrl(channelMerchantBusinessContext.isTest());
            if (StringUtils.hasText(merchantWechatConfigDto.getAppId())) {
                Map<String, Object> params = new HashMap<>();
                params.put("merchantNo", merchantAccessInfo.getSubMchId());
                params.put("orderNo", System.currentTimeMillis() + "");
                params.put("subMerchantNo", merchantAccessAuth.getSubMchId());
                params.put("appId", merchantWechatConfigDto.getAppId());
                CommonResult<HeliWechatConfigInitRes> commonResult = heliPayAccessRequest(accessUrl, "addAppIdDevConfig", heliPayConfig, JsonUtils.toJsonString(params),
                        HeliWechatConfigInitRes.class);
                log.info("合利宝 微信appId配置配置 返回参数 :{}", JsonUtils.toJsonString(commonResult));
                if (!commonResult.isSuccess()) {
                    channelMerchantBusinessContext.setProcessStatus(false);
                    channelMerchantBusinessContext.setRemark(commonResult.getMsg());
                }
                HeliWechatConfigInitRes heliWechatConfigInitRes = commonResult.getData();
                if ("FAIL".equals(heliWechatConfigInitRes.getStatus())) {
                    channelMerchantBusinessContext.setProcessStatus(false);
                    channelMerchantBusinessContext.setRemark(heliWechatConfigInitRes.getWxPublicConfigChannelMsg());
                }

            }
            String jsAPIPath = merchantWechatConfigDto.getJsAPIPath();
            if (StringUtils.hasText(jsAPIPath)) {
                Map<String, Object> params = new HashMap<>();
                params.put("merchantNo", merchantAccessInfo.getSubMchId());
                params.put("orderNo", System.currentTimeMillis() + "");
                params.put("subMerchantNo", merchantAccessAuth.getSubMchId());
                if (!merchantWechatConfigDto.getJsAPIPath().endsWith(StringPool.SLASH)) {
                    jsAPIPath = jsAPIPath + StringPool.SLASH;
                }
                params.put("authPayDir", jsAPIPath);
                CommonResult<HeliWechatConfigInitRes> commonResult = heliPayAccessRequest(accessUrl, "addAuthPayDirsDevConfig", heliPayConfig, JsonUtils.toJsonString(params),
                        HeliWechatConfigInitRes.class);
                log.info("合利宝 微信授权目录配置 返回参数 :{}", JsonUtils.toJsonString(commonResult));
                if (!commonResult.isSuccess()) {
                    channelMerchantBusinessContext.setProcessStatus(false);
                    channelMerchantBusinessContext.setRemark(commonResult.getMsg());
                }
                HeliWechatConfigInitRes heliWechatConfigInitRes = commonResult.getData();
                if ("FAIL".equals(heliWechatConfigInitRes.getStatus())) {
                    channelMerchantBusinessContext.setProcessStatus(false);
                    channelMerchantBusinessContext.setRemark(heliWechatConfigInitRes.getWxPublicConfigChannelMsg());
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            log.error("合利宝微信配置add请求失败,失败信息 message: {}", e.getMessage());
            channelMerchantBusinessContext.setRemark("合利宝微信配置add请求失败,失败信息" + e.getMessage());
            channelMerchantBusinessContext.setProcessStatus(Boolean.FALSE);
            // channelMerchantBusinessContext.setAccessStatus(MerchantEnum.ACCESS_STATUS.APPROVE_REFUSE);
        }
    }

    /**
     * 微信参数配置查询
     *
     * @param channelMerchantAccessAuthQueryContext
     */
    public void processWxConfigQuery(ChannelMerchantAccessAuthQueryContext channelMerchantAccessAuthQueryContext) {

    }

    /**
     * 微信参数配置查询
     *
     * @param channelMerchantAccessAuthQueryContext
     */
    public void processWxAuthQuery(ChannelMerchantAccessAuthQueryContext channelMerchantAccessAuthQueryContext) {
        CommonResult<HeliPayConfig> heliPayConfigCommonResult = heliPayConfig(channelMerchantAccessAuthQueryContext.getProviderChannelConfig(),
                channelMerchantAccessAuthQueryContext.isTest());
        // 配置转换
        if (!heliPayConfigCommonResult.isSuccess()) {
            channelMerchantAccessAuthQueryContext.setRemark(heliPayConfigCommonResult.getMsg());
            channelMerchantAccessAuthQueryContext.setProcessStatus(Boolean.FALSE);
            return;
        }
        HeliPayConfig heliPayConfig = heliPayConfigCommonResult.getData();
        // 1. 数据初始化
        MerchantAccessInfoDO merchantAccessInfo = channelMerchantAccessAuthQueryContext.getMerchantAccessInfo();
        try {
            List<MerchantAccessAuthDO> merchantAccessAuthList = new ArrayList<>();
            String accessUrl = accessUrl(channelMerchantAccessAuthQueryContext.isTest());
            Map<String, String> params = new HashMap<>();
            params.put("merchantNo", merchantAccessInfo.getSubMchId());
            params.put("orderNo", System.currentTimeMillis() + "");
            params.put("appPayType", "WXPAY");
            CommonResult<HeliPayAuthQueryRes> commonResult = heliPayAccessRequest(accessUrl, "appApplyQuery", heliPayConfig, JsonUtils.toJsonString(params),
                    HeliPayAuthQueryRes.class);
            log.info("合利宝 微信报备查询 返回参数 :{}", JsonUtils.toJsonString(commonResult));
            HeliPayAuthQueryRes heliPayAuthQueryRes = commonResult.getData();
            if (heliPayAuthQueryRes != null) {
                if ("SUCCESS".equals(heliPayAuthQueryRes.getStatus())) {
                    List<HeliPayAuthQueryRes.HeliPayPartnerAuthQueryRes> threePartnerNoData = heliPayAuthQueryRes.getThreePartnerNoData();
                    if (!CollectionUtils.isEmpty(threePartnerNoData)) {
                        Map<String, List<HeliPayAuthQueryRes.HeliPayPartnerAuthQueryRes>> collect = threePartnerNoData.stream().collect(Collectors.groupingBy(
                                heliPayPartnerAuthQueryRes -> heliPayPartnerAuthQueryRes.getThreePartnerNo() + "_" + heliPayPartnerAuthQueryRes.getChannelMerchantNo()));
                        collect.forEach((key, value) -> {
                            HeliPayAuthQueryRes.HeliPayPartnerAuthQueryRes partnerAuthQueryRes = value.get(0);
                            MerchantAccessAuthDO merchantAccessAuthDO = new MerchantAccessAuthDO();
                            merchantAccessAuthDO.setType(PayEnums.PAY_TYPE.WECHAT.getCode());
                            if (StringUtils.hasText(partnerAuthQueryRes.getConfirmStatus())) {
                                switch (partnerAuthQueryRes.getConfirmStatus()) {
                                    case "CONFIRM_REJECTED":
                                        merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.REJECT.getCode());
                                        break;
                                    case "CONFIRMING":
                                        merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.APPROVEING.getCode());
                                        break;
                                    case "CONFIRM_CONTACT":
                                        merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.WAIT_CONFIRM.getCode());
                                        break;
                                    case "CONFIRM_LEGALPERSON":
                                        merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.WAIT_AUTH.getCode());
                                        break;
                                    case "CONFIRM_PASSED":
                                        merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.APPROVE.getCode());
                                        break;
                                    case "CONFIRM_FREEZED":
                                        merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.FROZEN.getCode());
                                        break;
                                    case "CONFIRM_CANCELED":
                                        merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.CANCEL.getCode());
                                        break;
                                    default:
                                }
                            }
                            else {
                                merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.APPROVEING.getCode());
                            }
                            if (StringUtils.hasText(partnerAuthQueryRes.getAuthorizeStatus())) {
                                switch (partnerAuthQueryRes.getAuthorizeStatus()) {
                                    case "AUTHORIZED":
                                        merchantAccessAuthDO.setAuthStatus(MerchantEnum.AUTH_STATUS_TYPE.AUTHORIZED.getCode());
                                        break;
                                    case "AUTHORIZED_FAIL":
                                        merchantAccessAuthDO.setAuthStatus(MerchantEnum.AUTH_STATUS_TYPE.AUTHORIZED_FAIL.getCode());
                                        break;
                                    default:
                                }
                            }
//                            merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.WAIT_CONFIRM.getCode());
                            merchantAccessAuthDO.setSubMchId(partnerAuthQueryRes.getThreePartnerNo());
                            merchantAccessAuthDO.setMchId(partnerAuthQueryRes.getChannelMerchantNo());
                            merchantAccessAuthDO.setSerialCode(partnerAuthQueryRes.getReportId());
                            merchantAccessAuthDO.setChannelJson(JsonUtils.toJsonString(partnerAuthQueryRes));
                            if (StringUtils.hasText(partnerAuthQueryRes.getQrCodeData())) {
                                byte[] imageBytes = Base64.getDecoder().decode(partnerAuthQueryRes.getQrCodeData());
                                merchantAccessAuthDO.setQrCodeArray(imageBytes);
                            }
                            merchantAccessAuthDO.setRejectReason(partnerAuthQueryRes.getReportFailedReason());
                            merchantAccessAuthList.add(merchantAccessAuthDO);
                        });
                    }
                }

            }
            channelMerchantAccessAuthQueryContext.setAuditStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.ALIPAY_AUTH);
            channelMerchantAccessAuthQueryContext.setMerchantAccessAuthList(merchantAccessAuthList);
        }
        catch (Exception e) {
            e.printStackTrace();
            log.error("合利宝微信报备查询查询请求失败,失败信息 message: {}", e.getMessage());
            channelMerchantAccessAuthQueryContext.setRemark("合利宝微信报备查询查询请求失败,失败信息" + e.getMessage());
            channelMerchantAccessAuthQueryContext.setProcessStatus(Boolean.FALSE);
        }
    }

    /**
     * 微信参数配置查询
     *
     * @param merchantAccessAuthQueryContext
     */
    public void processAliAuthQuery(ChannelMerchantAccessAuthQueryContext merchantAccessAuthQueryContext) {
        CommonResult<HeliPayConfig> heliPayConfigCommonResult = heliPayConfig(merchantAccessAuthQueryContext.getProviderChannelConfig(), merchantAccessAuthQueryContext.isTest());
        // 配置转换
        if (!heliPayConfigCommonResult.isSuccess()) {
            merchantAccessAuthQueryContext.setRemark(heliPayConfigCommonResult.getMsg());
            merchantAccessAuthQueryContext.setProcessStatus(Boolean.FALSE);
            return;
        }
        HeliPayConfig heliPayConfig = heliPayConfigCommonResult.getData();
        // 1. 数据初始化
        MerchantAccessInfoDO merchantAccessInfo = merchantAccessAuthQueryContext.getMerchantAccessInfo();
        try {
            List<MerchantAccessAuthDO> merchantAccessAuthList = new ArrayList<>();

            String accessUrl = accessUrl(merchantAccessAuthQueryContext.isTest());
            Map<String, String> params = new HashMap<>();
            params.put("merchantNo", merchantAccessInfo.getSubMchId());
            params.put("orderNo", System.currentTimeMillis() + "");
            params.put("appPayType", "ALIPAY");
            CommonResult<HeliPayAuthQueryRes> commonResult = heliPayAccessRequest(accessUrl, "appApplyQuery", heliPayConfig, JsonUtils.toJsonString(params),
                    HeliPayAuthQueryRes.class);
            log.info("合利宝 支付宝报备查询 返回参数 :{}", JsonUtils.toJsonString(commonResult));
            HeliPayAuthQueryRes heliPayAuthQueryRes = commonResult.getData();
            if (heliPayAuthQueryRes != null) {
                if ("SUCCESS".equals(heliPayAuthQueryRes.getStatus())) {
                    List<HeliPayAuthQueryRes.HeliPayPartnerAuthQueryRes> threePartnerNoData = heliPayAuthQueryRes.getThreePartnerNoData();
                    if (!CollectionUtils.isEmpty(threePartnerNoData)) {
                        Map<String, List<HeliPayAuthQueryRes.HeliPayPartnerAuthQueryRes>> collect = threePartnerNoData.stream().collect(Collectors.groupingBy(
                                heliPayPartnerAuthQueryRes -> heliPayPartnerAuthQueryRes.getThreePartnerNo() + "_" + heliPayPartnerAuthQueryRes.getChannelMerchantNo()));
                        collect.forEach((key, value) -> {
                            HeliPayAuthQueryRes.HeliPayPartnerAuthQueryRes partnerAuthQueryRes = value.get(0);
                            MerchantAccessAuthDO merchantAccessAuthDO = new MerchantAccessAuthDO();
                            merchantAccessAuthDO.setType(PayEnums.PAY_TYPE.ALIPAY.getCode());
                            if (StringUtils.hasText(partnerAuthQueryRes.getConfirmStatus())) {
                                switch (partnerAuthQueryRes.getConfirmStatus()) {
                                    case "CONFIRM_REJECTED":
                                        merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.REJECT.getCode());
                                        break;
                                    case "CONFIRMING":
                                        merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.APPROVEING.getCode());
                                        break;
                                    case "CONFIRM_CONTACT":
                                        merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.WAIT_CONFIRM.getCode());
                                        break;
                                    case "CONFIRM_LEGALPERSON":
                                        merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.WAIT_AUTH.getCode());
                                        break;
                                    case "CONFIRM_PASSED":
                                        merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.APPROVE.getCode());
                                        break;
                                    case "CONFIRM_FREEZED":
                                        merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.FROZEN.getCode());
                                        break;
                                    case "CONFIRM_CANCELED":
                                        merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.CANCEL.getCode());
                                        break;
                                    default:
                                }
                            }
                            else {
                                merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.APPROVEING.getCode());
                            }
                            if (StringUtils.hasText(partnerAuthQueryRes.getAuthorizeStatus())) {
                                switch (partnerAuthQueryRes.getAuthorizeStatus()) {
                                    case "AUTHORIZED":
                                        merchantAccessAuthDO.setAuthStatus(MerchantEnum.AUTH_STATUS_TYPE.AUTHORIZED.getCode());
                                        break;
                                    case "AUTHORIZED_FAIL":
                                        merchantAccessAuthDO.setAuthStatus(MerchantEnum.AUTH_STATUS_TYPE.AUTHORIZED_FAIL.getCode());
                                        break;
                                    default:
                                }
                            }
//                            merchantAccessAuthDO.setStatus(MerchantEnum.MERCHANT_AUTH_STATUS.WAIT_CONFIRM.getCode());
                            merchantAccessAuthDO.setSubMchId(partnerAuthQueryRes.getThreePartnerNo());
                            merchantAccessAuthDO.setMchId(partnerAuthQueryRes.getChannelMerchantNo());
                            merchantAccessAuthDO.setSerialCode(partnerAuthQueryRes.getReportId());
                            merchantAccessAuthDO.setChannelJson(JsonUtils.toJsonString(partnerAuthQueryRes));
                            if (StringUtils.hasText(partnerAuthQueryRes.getQrCodeData())) {
                                byte[] imageBytes = Base64.getDecoder().decode(partnerAuthQueryRes.getQrCodeData());
                                merchantAccessAuthDO.setQrCodeArray(imageBytes);
                            }
                            merchantAccessAuthDO.setRejectReason(partnerAuthQueryRes.getReportFailedReason());
                            merchantAccessAuthList.add(merchantAccessAuthDO);
                        });
                    }
                }

            }
            merchantAccessAuthQueryContext.setAuditStatus(MerchantEnum.CHANNEL_CONFIG_STATUS.FINISH);
            merchantAccessAuthQueryContext.setMerchantAccessAuthList(merchantAccessAuthList);
        }
        catch (Exception e) {
            e.printStackTrace();
            log.error("合利宝支付宝报备信息查询请求失败,失败信息 message: {}", e.getMessage());
            merchantAccessAuthQueryContext.setRemark("合利宝支付宝报备信息查询请求失败,失败信息" + e.getMessage());
            merchantAccessAuthQueryContext.setProcessStatus(Boolean.FALSE);
        }
    }
}
